<template>
  <div class="directory-manager">
    <div class="header">
      <h2>目录管理</h2>
    </div>

    <div class="content-layout">
      <!-- 左侧目录树 -->
      <div class="tree-container">
        <div class="tree-header">
          <span>目录结构</span>
        </div>
        <el-tree
          :data="dashboardFolders"
          node-key="id"
          default-expand-all
          draggable
          :allow-drop="handleAllowDrop"
          :allow-drag="handleAllowDrag"
          @node-drop="handleNodeDrop"
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <div class="node-content">
                <el-icon><Folder /></el-icon>
                <span>{{ data.name }}</span>
              </div>
            </div>
          </template>
        </el-tree>
      </div>

      <!-- 右侧配置区域 -->
      <div class="config-container" v-if="currentFolder">
        <div class="config-header">
          <span>{{ currentFolder.name }} - 配置</span>
          <el-button type="primary" @click="handleSaveAll">保存</el-button>
        </div>
        <div class="config-content">
          <el-tabs v-model="activeTab">
            <!-- 目录配置 -->
            <el-tab-pane label="目录配置" name="directory">
              <el-form label-position="top">
                <el-form-item label="目录名称">
                  <el-input v-model="editingFolder.name" placeholder="请输入目录名称" />
                </el-form-item>
                <el-form-item>
                  <div class="button-group">
                    <el-button type="primary" @click="handleAddSubDirectory(currentFolder)">
                      <el-icon><Plus /></el-icon>
                      添加子目录
                    </el-button>
                    <el-button type="danger" @click="handleDelete(currentFolder)">
                      <el-icon><Delete /></el-icon>
                      删除目录
                    </el-button>
                  </div>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- 表单配置 -->
            <el-tab-pane label="表单配置" name="form">
              <el-form label-position="top">
                <el-form-item label="选择表单">
                  <el-select
                    v-model="selectedFormIds"
                    multiple
                    placeholder="请选择表单"
                    style="width: 100%"
                    @change="handleFormSelectionChange"
                  >
                    <el-option
                      v-for="form in visibleForms"
                      :key="form.name"
                      :label="form.name"
                      :value="form.name"
                    >
                      <div class="form-option">
                        <span class="form-name">{{ form.name }}</span>
                        <span class="form-path">data/forms/{{ form.name }}.json</span>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              
              <div class="selected-forms">
                <h4>已选择的表单</h4>
                <el-table :data="currentFolder.forms" border style="width: 100%">
                  <el-table-column prop="name" label="表单名称">
                    <template #default="{ row }">
                      <span class="form-name">{{ row.name }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="文件路径" min-width="200">
                    <template #default="{ row }">
                      <span class="form-path">data/forms/{{ row.name }}.json</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template #default="{ row }">
                      <el-button type="danger" size="small" @click="handleRemoveForm(row)">
                        移除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>

            <!-- 链接配置 -->
            <el-tab-pane label="链接配置" name="link">
              <el-form label-position="top">
                <el-form-item label="链接地址">
                  <el-input v-model="editingFolder.link" placeholder="请输入链接地址" />
                </el-form-item>
                <el-form-item label="链接说明">
                  <el-input
                    type="textarea"
                    v-model="editingFolder.description"
                    placeholder="请输入链接说明"
                    :rows="3"
                  />
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <!-- 欢迎页面 -->
      <div class="welcome-container" v-else>
        <div class="welcome-content">
          <el-empty description="请选择左侧目录或点击下方按钮创建新目录">
            <el-button type="primary" @click="handleAddRootDirectory">
              <el-icon><Plus /></el-icon>
              添加根目录
            </el-button>
          </el-empty>
        </div>
      </div>
    </div>

    <!-- 新建目录弹窗 -->
    <el-dialog
      v-model="showNewDirDialog"
      :title="currentFolder ? '新建子目录' : '新建根目录'"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="newDirForm" :rules="dirRules" ref="newDirFormRef">
        <el-form-item label="目录名称" prop="name">
          <el-input v-model="newDirForm.name" placeholder="请输入目录名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showNewDirDialog = false">取消</el-button>
          <el-button type="primary" @click="handleCreateDirectory">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重命名目录弹窗 -->
    <el-dialog
      v-model="showRenameDialog"
      title="重命名目录"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="renameForm" :rules="dirRules" ref="renameFormRef">
        <el-form-item label="目录名称" prop="name">
          <el-input v-model="renameForm.name" placeholder="请输入新的目录名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRenameDialog = false">取消</el-button>
          <el-button type="primary" @click="handleRenameConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 表单管理对话框 -->
    <el-dialog
      v-model="showFormManageDialog"
      title="管理表单"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form>
        <el-form-item label="选择表单">
          <el-select
            v-model="selectedFormIds"
            multiple
            placeholder="请选择表单"
            style="width: 100%"
          >
            <el-option
              v-for="form in visibleForms"
              :key="form.name"
              :label="form.name"
              :value="form.name"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showFormManageDialog = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmFormSelection">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Plus, Folder, Edit, Delete, Document, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import axios from 'axios'

const API_BASE_URL = 'http://localhost:5000/api/nav'
const API_BASE_URL_FORM = 'http://localhost:5000/api/'


interface Form {
  id: string
  name: string
  type: string
  folderId: string
  path?: string
}

interface FormFile {
  name: string
  path: string
}

interface Folder {
  id: string
  name: string
  type: 'dashboard'
  children: Folder[]
  forms: Form[]
  link?: string
  description?: string
}

const props = defineProps<{
  availableForms: Form[]
}>()

// 响应式变量
const dashboardFolders = ref<Folder[]>([])
const showNewDirDialog = ref(false)
const showRenameDialog = ref(false)
const showFormManageDialog = ref(false)
const currentFolder = ref<Folder | null>(null)
const newDirForm = ref({ name: '' })
const renameForm = ref({ name: '' })
const selectedFormIds = ref<string[]>([])
const newDirFormRef = ref<FormInstance | null>(null)
const renameFormRef = ref<FormInstance | null>(null)
const activeTab = ref('directory')
const editingFolder = ref<{
  name: string
  link?: string
  description?: string
}>({
  name: '',
  link: '',
  description: ''
})

const dirRules = {
  name: [
    { required: true, message: '请输入目录名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

const emit = defineEmits<{
  'structure-updated': [folders: Folder[]]
}>()

// 获取所有可见表单
const visibleForms = ref<Form[]>([])

// 加载所有可见表单
const loadVisibleForms = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL_FORM}/form/list`)
    if (response.data.code === 0) {
      // 转换表单数据格式
      visibleForms.value = (response.data.data || []).map((form: FormFile) => ({
        id: form.name,
        name: form.name,
        type: 'form',
        path: form.path,
        folderId: ''  // 初始化为空字符串
      }))
    } else {
      throw new Error(response.data.message || '加载表单失败')
    }
  } catch (error) {
    console.error('加载表单错误:', error)
    ElMessage.error('加载表单失败')
  }
}

// 加载目录结构
const loadStructure = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/dashboard/structure`)
    if (response.data.code === 0) {
      dashboardFolders.value = response.data.data || []
      // 如果当前有选中的目录，更新它的信息
      if (currentFolder.value) {
        const findFolder = (folders: Folder[]): Folder | null => {
          for (const folder of folders) {
            if (folder.id === currentFolder.value!.id) {
              return folder
            }
            if (folder.children) {
              const found = findFolder(folder.children)
              if (found) return found
            }
          }
          return null
        }
        
        const updatedFolder = findFolder(dashboardFolders.value)
        if (updatedFolder) {
          currentFolder.value = updatedFolder
          editingFolder.value = {
            name: updatedFolder.name,
            link: updatedFolder.link || '',
            description: updatedFolder.description || ''
          }
        }
      }
    } else {
      throw new Error(response.data.message || '加载目录结构失败')
    }
  } catch (error) {
    console.error('加载目录结构错误:', error)
    ElMessage.error('加载目录结构失败')
  }
}

// 在组件挂载时加载数据
onMounted(async () => {
  await loadStructure()
  await loadVisibleForms()
})

// 添加根目录
const handleAddRootDirectory = () => {
  currentFolder.value = null
  newDirForm.value.name = ''
  showNewDirDialog.value = true
}

// 添加子目录
const handleAddSubDirectory = (folder: Folder) => {
  currentFolder.value = folder
  newDirForm.value.name = ''
  showNewDirDialog.value = true
}

// 获取层级名称
const getLevelName = (level: number) => {
  return level === 1 ? '子目录' : `${level}级子目录`
}

// 判断是否可以上移
const canMoveUp = (folder: Folder) => {
  const parent = findParentFolder(folder)
  const siblings = parent ? parent.children : dashboardFolders.value
  const index = siblings.findIndex(f => f.id === folder.id)
  return index > 0
}

// 判断是否可以下移
const canMoveDown = (folder: Folder) => {
  const parent = findParentFolder(folder)
  const siblings = parent ? parent.children : dashboardFolders.value
  const index = siblings.findIndex(f => f.id === folder.id)
  return index < siblings.length - 1
}

// 查找父目录
const findParentFolder = (folder: Folder): Folder | null => {
  const find = (folders: Folder[]): Folder | null => {
    for (const f of folders) {
      if (f.children.some(child => child.id === folder.id)) {
        return f
      }
      const found = find(f.children)
      if (found) return found
    }
    return null
  }
  return find(dashboardFolders.value)
}

// 处理上移
const handleMoveUp = async (folder: Folder) => {
  const parent = findParentFolder(folder)
  const siblings = parent ? parent.children : dashboardFolders.value
  const index = siblings.findIndex(f => f.id === folder.id)
  if (index > 0) {
    const temp = siblings[index]
    siblings[index] = siblings[index - 1]
    siblings[index - 1] = temp
    await saveStructure()
    emit('structure-updated', dashboardFolders.value)
  }
}

// 处理下移
const handleMoveDown = async (folder: Folder) => {
  const parent = findParentFolder(folder)
  const siblings = parent ? parent.children : dashboardFolders.value
  const index = siblings.findIndex(f => f.id === folder.id)
  if (index < siblings.length - 1) {
    const temp = siblings[index]
    siblings[index] = siblings[index + 1]
    siblings[index + 1] = temp
    await saveStructure()
    emit('structure-updated', dashboardFolders.value)
  }
}

// 创建目录
const handleCreateDirectory = async () => {
  if (!newDirFormRef.value) return
  
  await newDirFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const newFolder: Folder = {
        id: `folder${Date.now()}`,
        name: newDirForm.value.name,
        type: 'dashboard',
        children: [],
        forms: []
      }

      if (currentFolder.value) {
        if (!currentFolder.value.children) {
          currentFolder.value.children = []
        }
        currentFolder.value.children.push(newFolder)
      } else {
        dashboardFolders.value = [...dashboardFolders.value, newFolder]
      }

      if (await saveStructure()) {
        showNewDirDialog.value = false
        newDirForm.value.name = ''
        ElMessage.success('目录创建成功')
      }
    }
  })
}

// 重命名目录
const handleRename = (folder: Folder) => {
  currentFolder.value = folder
  renameForm.value.name = folder.name
  showRenameDialog.value = true
}

// 确认重命名
const handleRenameConfirm = async () => {
  if (!renameFormRef.value || !currentFolder.value) return
  
  await renameFormRef.value.validate(async (valid: boolean) => {
    if (valid && currentFolder.value) {
      currentFolder.value.name = renameForm.value.name
      // 保存更新后的结构
      await saveStructure()
      showRenameDialog.value = false
      ElMessage.success('目录重命名成功')
    }
  })
}

// 处理管理表单
const handleManageForms = (folder: Folder) => {
  currentFolder.value = folder
  // 将当前目录的表单名称转换为选中状态
  selectedFormIds.value = folder.forms.map(form => form.name)
  showFormManageDialog.value = true
}

// 确认选择表单
const handleConfirmFormSelection = async () => {
  if (!currentFolder.value) return
  
  try {
    // 获取选中的表单详情
    const selectedForms = visibleForms.value.filter(form => 
      selectedFormIds.value.includes(form.id)
    )
    
    // 更新当前目录的表单
    currentFolder.value.forms = selectedForms.map(form => ({
      id: form.id,
      name: form.name,
      type: form.type,
      path: form.path,
      folderId: currentFolder.value!.id
    }))
    
    // 保存更新后的结构
    await saveStructure()
    
    showFormManageDialog.value = false
    ElMessage.success('表单管理成功')
    
    // 触发结构更新事件
    emit('structure-updated', dashboardFolders.value)
  } catch (error) {
    console.error('保存表单管理错误:', error)
    ElMessage.error('保存失败')
  }
}

// 删除目录
const handleDelete = async (folder: Folder) => {
  try {
    await ElMessageBox.confirm('确定要删除该目录吗？目录下的所有内容将被删除', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const deleteFolder = (folders: Folder[]): Folder[] => {
      return folders.filter(f => {
        if (f.id === folder.id) return false
        if (f.children) {
          f.children = deleteFolder(f.children)
        }
        return true
      })
    }

    dashboardFolders.value = deleteFolder(dashboardFolders.value)
    
    // 保存更新后的结构
    await saveStructure()
    ElMessage.success('目录删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除目录错误:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 保存目录结构
const saveStructure = async () => {
  try {
    const response = await axios.post(`${API_BASE_URL}/dashboard/structure`, {
      structure: dashboardFolders.value
    })
    
    if (response.data.code === 0) {
      // 触发结构更新事件
      emit('structure-updated', dashboardFolders.value)
      return true
    } else {
      throw new Error(response.data.message || '保存失败')
    }
  } catch (error) {
    console.error('保存目录结构错误:', error)
    ElMessage.error('保存失败，请检查网络连接')
    return false
  }
}

// 处理拖拽
const handleAllowDrop = (draggingNode: any, dropNode: any, type: 'prev' | 'next' | 'inner') => {
  // 防止拖拽到自身或子节点
  const draggingData = draggingNode.data
  const dropData = dropNode.data
  
  if (draggingData.id === dropData.id) return false
  
  // 检查是否是拖拽到子节点
  const isChild = (parent: Folder, child: Folder): boolean => {
    if (parent.children) {
      return parent.children.some(node => 
        node.id === child.id || isChild(node, child)
      )
    }
    return false
  }
  
  return !isChild(draggingData, dropData)
}

const handleAllowDrag = (node: any) => {
  return true // 允许所有节点拖拽
}

const handleNodeDrop = async (draggingNode: any, dropNode: any, type: string) => {
  // 更新数据结构
  const updateStructure = () => {
    const draggingData = draggingNode.data
    const dropData = dropNode.data
    
    // 先从原位置移除
    const removeFromParent = (folders: Folder[], id: string) => {
      for (let i = 0; i < folders.length; i++) {
        if (folders[i].id === id) {
          folders.splice(i, 1)
          return true
        }
        if (folders[i].children) {
          if (removeFromParent(folders[i].children, id)) {
            return true
          }
        }
      }
      return false
    }
    
    removeFromParent(dashboardFolders.value, draggingData.id)
    
    // 添加到新位置
    if (type === 'inner') {
      if (!dropData.children) dropData.children = []
      dropData.children.push(draggingData)
    } else {
      const parent = findParentFolder(dropData) || { children: dashboardFolders.value }
      const index = parent.children.findIndex(item => item.id === dropData.id)
      parent.children.splice(type === 'prev' ? index : index + 1, 0, draggingData)
    }
  }
  
  updateStructure()
  await saveStructure()
  emit('structure-updated', dashboardFolders.value)
}

// 移除表单
const handleRemoveForm = async (form: Form) => {
  if (!currentFolder.value) return
  
  try {
    await ElMessageBox.confirm('确定要移除该表单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    currentFolder.value.forms = currentFolder.value.forms.filter(f => f.id !== form.id)
    await saveStructure()
    ElMessage.success('表单移除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除表单错误:', error)
      ElMessage.error('移除失败')
    }
  }
}

// 处理节点点击
const handleNodeClick = (data: Folder) => {
  currentFolder.value = data
  editingFolder.value = {
    name: data.name,
    link: data.link || '',
    description: data.description || ''
  }
  // 更新选中的表单
  selectedFormIds.value = data.forms.map(form => form.id)
}

// 处理表单选择变化
const handleFormSelectionChange = async (selectedIds: string[]) => {
  if (!currentFolder.value) return

  try {
    // 获取选中的表单详情
    const selectedForms = visibleForms.value.filter(form => 
      selectedIds.includes(form.id)
    )
    
    // 更新当前目录的表单
    currentFolder.value.forms = selectedForms.map(form => ({
      id: form.id,
      name: form.name,
      type: form.type,
      path: form.path,
      folderId: currentFolder.value!.id
    }))
    
    // 保存更新后的结构
    const response = await axios.post(`${API_BASE_URL}/dashboard/structure`, {
      structure: dashboardFolders.value
    })

    if (response.data.code === 0) {
      ElMessage.success('表单配置已更新')
      // 重新加载目录结构
      await loadStructure()
      // 触发结构更新事件
      emit('structure-updated', dashboardFolders.value)
    } else {
      throw new Error(response.data.message || '保存失败')
    }
  } catch (error) {
    console.error('更新表单配置错误:', error)
    ElMessage.error('更新失败，请检查网络连接')
    // 恢复选择状态
    selectedFormIds.value = currentFolder.value.forms.map(form => form.id)
  }
}

// 保存所有更改
const handleSaveAll = async () => {
  if (!currentFolder.value) return

  try {
    // 更新当前目录的信息
    const updateFolder = (folders: Folder[]) => {
      for (let folder of folders) {
        if (folder.id === currentFolder.value!.id) {
          folder.name = editingFolder.value.name
          folder.link = editingFolder.value.link
          folder.description = editingFolder.value.description
          return true
        }
        if (folder.children && folder.children.length > 0) {
          if (updateFolder(folder.children)) {
            return true
          }
        }
      }
      return false
    }

    // 更新目录结构
    updateFolder(dashboardFolders.value)

    // 保存到后端
    const response = await axios.post(`${API_BASE_URL}/dashboard/structure`, {
      structure: dashboardFolders.value
    })

    if (response.data.code === 0) {
      ElMessage.success('保存成功')
      // 重新加载目录结构
      await loadStructure()
      // 触发结构更新事件
      emit('structure-updated', dashboardFolders.value)
    } else {
      throw new Error(response.data.message || '保存失败')
    }
  } catch (error) {
    console.error('保存错误:', error)
    ElMessage.error('保存失败，请检查网络连接')
  }
}
</script>

<style scoped>
.directory-manager {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  color: #303133;
}

.header h2 {
  color: #303133;
  margin: 0 0 20px 0;
}

.content-layout {
  display: flex;
  gap: 20px;
  flex: 1;
  min-height: 0;
}

.tree-container {
  width: 33.33%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: auto;
}

.config-container {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

.welcome-container {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tree-header {
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5f7fa;
}

.tree-header span {
  color: #303133;
  font-weight: 500;
}

.config-header {
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f5f7fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.config-content {
  padding: 16px;
  flex: 1;
  overflow: auto;
}

.button-group {
  display: flex;
  gap: 12px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-content .el-icon {
  color: #409EFF;
}

.node-content span {
  color: #303133;
  font-size: 14px;
}

.selected-forms {
  margin-top: 20px;
}

.selected-forms h4 {
  margin-bottom: 12px;
  color: #303133;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-tree-node__content) {
  height: 36px;
}

:deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
}

:deep(.el-form-item__label) {
  color: #303133;
  font-weight: 500;
}

:deep(.el-tabs__content) {
  padding: 20px 0;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}
</style> 